import 'package:azring/common/res/gaps.dart';
import 'package:azring/entity/health_questionnaire.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/core/repository/default_api.dart';
import 'package:azring/services/ring_service.dart';
import 'package:azring/gen/assets.gen.dart';
import 'package:azring/pages/action/routes.dart';
import 'package:azring/pages/status/routes.dart';
import 'package:azring/pages/status/status_logic.dart';

class QuestionnaireView extends StatefulWidget {
  const QuestionnaireView({super.key});

  @override
  State<QuestionnaireView> createState() => _QuestionnaireViewState();
}

class _QuestionnaireViewState extends State<QuestionnaireView> {
  final PageController _pageLogic = PageController();
  int _current = 0;

  // 个人信息字段控制器
  final TextEditingController _nicknameLogic = TextEditingController();
  final TextEditingController _professionLogic = TextEditingController();
  final FocusNode _nicknameFocus = FocusNode();
  final FocusNode _professionFocus = FocusNode();

  // 选择的选项
  String? _selectedBirthDate;
  String? _selectedGender; // 存储性别的 value
  String? _selectedGenderLabel; // 存储性别的 label 用于显示
  String? _selectedHeight;
  String? _selectedWeight;

  // 性别选项数据
  List<Map<String, String>> _genderOptions = [];

  // 问卷选项选择状态
  Map<int, List<String>> _selectedOptions = {}; // 存储每个问题的选择

  @override
  void initState() {
    super.initState();
    _nicknameFocus.addListener(_onFocusChange);
    _professionFocus.addListener(_onFocusChange);
    _loadGenderOptions();
  }

  /// 加载性别选项
  Future<void> _loadGenderOptions() async {
    try {
      final response = await DefaultApi().dataTypeGet<Map<String, dynamic>>(
        dictType: 'sys_user_sex',
        isShowErrMsg: false,
      );

      if (response != null && response['data'] != null) {
        final List<dynamic> dataList = response['data'];
        final List<Map<String, String>> options = dataList.map((item) {
          return <String, String>{
            'label': item['dictLabel']?.toString() ?? '',
            'value': item['dictValue']?.toString() ?? '',
          };
        }).toList();

        if (mounted) {
          setState(() {
            _genderOptions = options;
          });
        }
      } else {
        _setDefaultGenderOptions();
      }
    } catch (e) {
      print('加载性别选项失败: $e');
      _setDefaultGenderOptions();
    }
  }

  void _setDefaultGenderOptions() {
    if (mounted) {
      setState(() {
        _genderOptions = <Map<String, String>>[
          <String, String>{'label': '男', 'value': '0'},
          <String, String>{'label': '女', 'value': '1'},
          <String, String>{'label': '未知', 'value': '2'},
        ];
      });
    }
  }

  void _onFocusChange() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void dispose() {
    _nicknameFocus.removeListener(_onFocusChange);
    _professionFocus.removeListener(_onFocusChange);
    _nicknameFocus.dispose();
    _professionFocus.dispose();
    super.dispose();
  }

  void _next() {
    if (_current < 5) {
      setState(() => _current++);
      _pageLogic.animateToPage(_current,
          duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
    } else {
      // 完成问卷后提交数据
      _submitQuestionnaire();
    }
  }

  void _previous() {
    if (_current > 0) {
      setState(() => _current--);
      _pageLogic.animateToPage(_current,
          duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
    }
  }

  @override
  Widget build(BuildContext context) {
    final titles = ['个人信息设置', '运动目标', '睡眠目标', '饮食目标', '情绪管理', '周期规划'];
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: _current != 0
            ? IconButton(
                icon: const Icon(
                  Icons.arrow_back_ios,
                  color: Colors.white,
                  size: 20,
                ),
                onPressed: _previous,
              )
            : null,
        title: const Text(
          '健康问卷',
          style: TextStyle(
            color: Colors.white,
            fontSize: 18,
            fontWeight: FontWeight.w500,
          ),
        ),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.only(left: 24, right: 24),
        child: Column(
          children: [
            _buildStepsWithTitle(titles),
            Gaps.vGap28,
            Expanded(
              child: PageView(
                controller: _pageLogic,
                physics: const NeverScrollableScrollPhysics(),
                children: [
                  _buildInfoStep(),
                  _buildQuestionStep(
                      '运动目标',
                      ['您目前的运动频率是？', '您平时每天的行走步数大约在？'],
                      [
                        [
                          '几乎不运动 (每周<1次)',
                          '偶尔运动 (每周1-2次)',
                          '经常运动 (每周3-4次)',
                          '规律运动 (每周5次及以上)'
                        ],
                        ['5000步以下', '5000-8000步', '8000-10000步', '10000步以上']
                      ],
                      0),
                  _buildQuestionStep(
                      '睡眠目标',
                      ['您通常睡眠总时长能达到几个小时?', '您需要多久才能入睡', '您夜间醒来次数?'],
                      [
                        ['少于6小时', '6-10小时', '超过10小时'],
                        ['很快 (15分钟内)', '一般 (30分钟左右)', '需要很长时间 (1小时)'],
                        ['几乎不醒', '1-2次', '3次及以上']
                      ],
                      2),
                  _buildQuestionStep(
                      '饮食目标',
                      ['您每天规律吃三餐吗?', '您每天喝多少水? (每杯水约250ml)', '您的健康目标是?'],
                      [
                        ['非常规律', '比较规律', '很不规律,经常不吃早餐或晚餐'],
                        ['少于4杯', '4-6杯', '7-8杯', '8杯以上'],
                        ['减脂/减重', '维持当前体重', '增肌/增重']
                      ],
                      5),
                  _buildQuestionStep(
                      '情绪管理',
                      ['过去一周,您感受到压力的评率是?', '您通常如何管理压力?(可多选)'],
                      [
                        ['几乎没有', '偶尔', '经常', '几乎一直'],
                        ['运动', '听音乐/冥想', '与他人倾述', '购物/娱乐', '默默承受']
                      ],
                      8),
                  _buildQuestionStep(
                      '周期规划',
                      ['您希望通过使用AZRing智能戒指，最主要想改善那个方面？', '您为达成健康目标，愿意执行多长周期？'],
                      [
                        [
                          '提升睡眠质量',
                          '增加运动量，减脂塑形',
                          '管理压力，平稳情绪',
                          '养成更健康的饮食作息习惯',
                          '全面了解身体健康数据'
                        ],
                        ['15天', '30天', '40天']
                      ],
                      10),
                ],
              ),
            ),
            if (_current != 0)
              Padding(
                padding: EdgeInsets.symmetric(vertical: 16.h),
                child: Container(
                  width: double.infinity,
                  height: 56.h,
                  decoration: BoxDecoration(
                    color: const Color(0xffF46425),
                    borderRadius: BorderRadius.circular(999.r),
                  ),
                  child: Material(
                    color: Colors.transparent,
                    child: InkWell(
                      onTap: _next,
                      borderRadius: BorderRadius.circular(999.r),
                      child: Center(
                        child: Text(
                          _current < 5 ? '继续' : '完成',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              )
          ],
        ),
      ),
    );
  }

  Widget _buildStepsWithTitle(List<String> titles) {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: List.generate(6, (i) {
            final bool isCurrent = i == _current;
            return AnimatedContainer(
              duration: const Duration(milliseconds: 250),
              width: isCurrent ? 119.w : 41.w,
              height: 20.h,
              decoration: BoxDecoration(
                color: isCurrent
                    ? const Color(0xffF46425)
                    : const Color(0xFF2A2A2A),
                borderRadius: BorderRadius.circular(4.r),
              ),
            );
          }),
        ),
        Gaps.vGap12,
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: List.generate(6, (i) {
            final bool isCurrent = i == _current;
            return Container(
              width: isCurrent ? 119.w : 41.w,
              child: isCurrent
                  ? Text(
                      titles[i],
                      style:
                          TextStyle(fontSize: 14.sp, color: Color(0xffF46425)),
                      textAlign: TextAlign.center,
                    )
                  : const SizedBox.shrink(),
            );
          }),
        ),
      ],
    );
  }

  Widget _buildInfoStep() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildInfoField('请输入昵称'),
        _buildInfoField('输入职业'),
        _buildInfoField('出生年月'),
        _buildInfoField('性别'),
        _buildInfoField('身高'),
        _buildInfoField('体重'),
        SizedBox(height: 61.h),
        Row(
          children: [
            Expanded(
              child: Container(
                height: 51.h,
                decoration: BoxDecoration(
                  color: const Color(0xFF450A0A),
                  borderRadius: BorderRadius.circular(999.r),
                ),
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: _submitBasicInfo,
                    borderRadius: BorderRadius.circular(999.r),
                    child: Center(
                      child: Text(
                        '完成',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
            SizedBox(width: 20.w),
            Expanded(
              child: Container(
                height: 51.h,
                decoration: BoxDecoration(
                  color: const Color(0xffF46425),
                  borderRadius: BorderRadius.circular(999.r),
                ),
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: _next,
                    borderRadius: BorderRadius.circular(999.r),
                    child: Center(
                      child: Text(
                        '继续完成问卷',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
        Gaps.vGap12,
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              width: 14.w,
              height: 14.h,
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xffF46425),
              ),
              child: const Icon(
                Icons.check,
                color: Colors.white,
                size: 10,
              ),
            ),
            SizedBox(width: 8.w),
            Expanded(
              child: Text(
                '注：完善个人信息将用于个性化生成基础的健康计划及指标。完善全部问卷内容将为您提供更加细化的健康规划,建议您继续完成问卷。',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.white.withOpacity(0.6),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildInfoField(String hint) {
    bool isInputField = hint == '请输入昵称' || hint == '输入职业';
    bool isFocused = false;

    if (isInputField) {
      if (hint == '请输入昵称') {
        isFocused = _nicknameFocus.hasFocus;
      } else if (hint == '输入职业') {
        isFocused = _professionFocus.hasFocus;
      }
    }

    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      height: 48.h,
      decoration: BoxDecoration(
        color: const Color(0xFF282528),
        borderRadius: BorderRadius.circular(8.r),
        border: isInputField && isFocused
            ? Border.all(color: const Color(0xFFF45757), width: 0.6)
            : null,
      ),
      child: isInputField
          ? TextField(
              controller: hint == '请输入昵称' ? _nicknameLogic : _professionLogic,
              focusNode: hint == '请输入昵称' ? _nicknameFocus : _professionFocus,
              style: const TextStyle(color: Colors.white, fontSize: 16),
              textInputAction: TextInputAction.done,
              onSubmitted: (value) {
                // 输入完成后自动失焦
                FocusScope.of(context).unfocus();
              },
              decoration: InputDecoration(
                hintText: hint,
                hintStyle: const TextStyle(color: Color(0xFF666666)),
                border: InputBorder.none,
                contentPadding: const EdgeInsets.symmetric(horizontal: 16),
              ),
            )
          : GestureDetector(
              onTap: () => _showBottomSheet(hint),
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      _getSelectedValue(hint),
                      style: TextStyle(
                        color: _getSelectedValue(hint) == hint
                            ? const Color(0xFF666666)
                            : Colors.white,
                        fontSize: 16,
                      ),
                    ),
                    const Icon(
                      Icons.keyboard_arrow_down,
                      color: Colors.white,
                      size: 20,
                    ),
                  ],
                ),
              ),
            ),
    );
  }

  String _getSelectedValue(String hint) {
    switch (hint) {
      case '出生年月':
        return _selectedBirthDate ?? hint;
      case '性别':
        return _selectedGenderLabel ?? hint;
      case '身高':
        return _selectedHeight ?? hint;
      case '体重':
        return _selectedWeight ?? hint;
      default:
        return hint;
    }
  }

  void _showBottomSheet(String hint) {
    // 先让所有输入框失焦，收起键盘
    _nicknameFocus.unfocus();
    _professionFocus.unfocus();
    FocusScope.of(context).unfocus();

    // 延迟一下再显示底部选择器，确保键盘已经收起
    Future.delayed(const Duration(milliseconds: 150), () {
      if (mounted) {
        showModalBottomSheet(
          context: context,
          backgroundColor: Colors.black,
          isScrollControlled: true,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
          ),
          builder: (context) => _buildBottomSheetContent(hint),
        );
      }
    });
  }

  Widget _buildBottomSheetContent(String hint) {
    switch (hint) {
      case '出生年月':
        return _buildDatePicker();
      case '性别':
        return _buildGenderPicker();
      case '身高':
        return _buildHeightPicker();
      case '体重':
        return _buildWeightPicker();
      default:
        return Container();
    }
  }

  Widget _buildDatePicker() {
    String tempYear = _selectedYear;
    String tempMonth = _selectedMonth;
    String tempDay = _selectedDay;

    return Container(
      height: 300.h,
      child: Column(
        children: [
          // 渐变头部
          Container(
            padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color(0xFF4E2101),
                  Color(0xFF181821),
                ],
              ),
              borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child:
                      const Text('取消', style: TextStyle(color: Colors.white)),
                ),
                const Text('出生年月',
                    style: TextStyle(color: Colors.white, fontSize: 18)),
                TextButton(
                  onPressed: () {
                    setState(() {
                      _selectedYear = tempYear;
                      _selectedMonth = tempMonth;
                      _selectedDay = tempDay;
                      _updateBirthDate();
                    });
                    Navigator.pop(context);
                  },
                  child: const Text('确认',
                      style: TextStyle(color: Color(0xffF46425))),
                ),
              ],
            ),
          ),
          Expanded(
            child: Row(
              children: [
                Expanded(
                    child: _buildScrollableDatePicker(
                        '年', (value) => tempYear = value)),
                Expanded(
                    child: _buildScrollableDatePicker(
                        '月', (value) => tempMonth = value)),
                Expanded(
                    child: _buildScrollableDatePicker(
                        '日', (value) => tempDay = value)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildGenderPicker() {
    print('构建性别选择器，选项数量: ${_genderOptions.length}');

    if (_genderOptions.isEmpty) {
      return SizedBox(
        height: 200.h,
        child: const Center(
          child: CircularProgressIndicator(color: Color(0xffF46425)),
        ),
      );
    }

    try {
      final genderLabels = _genderOptions
          .map((e) => (e['label'] ?? '') as String)
          .where((label) => label.isNotEmpty)
          .toList();

      print('性别标签列表: $genderLabels');

      if (genderLabels.isEmpty) {
        print('性别标签列表为空');
        return SizedBox(
          height: 200.h,
          child: const Center(
            child: Text('暂无性别选项', style: TextStyle(color: Colors.white)),
          ),
        );
      }

      String tempSelectedLabel = _selectedGenderLabel ?? genderLabels[0];
      String tempSelectedValue =
          _selectedGender ?? (_genderOptions[0]['value'] as String? ?? '0');

      return SizedBox(
        height: 200.h,
        child: Column(
          children: [
            // 渐变头部
            Container(
              padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
              decoration: const BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Color(0xFF4E2101),
                    Color(0xFF181821),
                  ],
                ),
                borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: () => Navigator.pop(context),
                    child:
                        const Text('取消', style: TextStyle(color: Colors.white)),
                  ),
                  const Text('性别',
                      style: TextStyle(color: Colors.white, fontSize: 18)),
                  TextButton(
                    onPressed: () {
                      setState(() {
                        _selectedGender = tempSelectedValue;
                        _selectedGenderLabel = tempSelectedLabel;
                      });
                      Navigator.pop(context);
                    },
                    child: const Text('确认',
                        style: TextStyle(color: Color(0xffF46425))),
                  ),
                ],
              ),
            ),
            Expanded(
              child: _buildScrollablePicker(
                items: genderLabels,
                initialValue: _selectedGenderLabel,
                onSelected: (label) {
                  print('选中性别标签: $label');
                  tempSelectedLabel = label;
                  // 根据 label 找到对应的 value
                  try {
                    final option = _genderOptions.firstWhere(
                      (e) => e['label'] == label,
                      orElse: () => _genderOptions[0],
                    );
                    tempSelectedValue = (option['value'] ?? '0') as String;
                    print('对应的值: $tempSelectedValue');
                  } catch (e) {
                    print('查找性别值失败: $e');
                  }
                },
              ),
            ),
          ],
        ),
      );
    } catch (e) {
      print('构建性别选择器失败: $e');
      return SizedBox(
        height: 200.h,
        child: Center(
          child: Text('加载失败: $e', style: const TextStyle(color: Colors.white)),
        ),
      );
    }
  }

  Widget _buildHeightPicker() {
    final heights = List.generate(100, (index) => '${120 + index}cm');
    String tempSelected = _selectedHeight ?? heights[50]; // 默认170cm

    return Container(
      height: 300.h,
      child: Column(
        children: [
          // 渐变头部
          Container(
            padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color(0xFF4E2101),
                  Color(0xFF181821),
                ],
              ),
              borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child:
                      const Text('取消', style: TextStyle(color: Colors.white)),
                ),
                const Text('身高',
                    style: TextStyle(color: Colors.white, fontSize: 18)),
                TextButton(
                  onPressed: () {
                    setState(() {
                      _selectedHeight = tempSelected;
                    });
                    Navigator.pop(context);
                  },
                  child: const Text('确认',
                      style: TextStyle(color: Color(0xffF46425))),
                ),
              ],
            ),
          ),
          Expanded(
            child: _buildScrollablePicker(
              items: heights,
              initialValue: _selectedHeight,
              onSelected: (value) {
                tempSelected = value;
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWeightPicker() {
    final weights = List.generate(100, (index) => '${30 + index}kg');
    String tempSelected = _selectedWeight ?? weights[30]; // 默认60kg

    return Container(
      height: 300.h,
      child: Column(
        children: [
          // 渐变头部
          Container(
            padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 16.w),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Color(0xFF4E2101),
                  Color(0xFF181821),
                ],
              ),
              borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child:
                      const Text('取消', style: TextStyle(color: Colors.white)),
                ),
                const Text('体重',
                    style: TextStyle(color: Colors.white, fontSize: 18)),
                TextButton(
                  onPressed: () {
                    setState(() {
                      _selectedWeight = tempSelected;
                    });
                    Navigator.pop(context);
                  },
                  child: const Text('确认',
                      style: TextStyle(color: Color(0xffF46425))),
                ),
              ],
            ),
          ),
          Expanded(
            child: _buildScrollablePicker(
              items: weights,
              initialValue: _selectedWeight,
              onSelected: (value) {
                tempSelected = value;
              },
            ),
          ),
        ],
      ),
    );
  }

  // 添加日期组件的状态变量
  String _selectedYear = '';
  String _selectedMonth = '';
  String _selectedDay = '';

  /// 更新出生日期显示和存储格式
  void _updateBirthDate() {
    if (_selectedYear.isNotEmpty &&
        _selectedMonth.isNotEmpty &&
        _selectedDay.isNotEmpty) {
      // 显示格式：1990年1月1日
      _selectedBirthDate =
          '${_selectedYear}年${int.parse(_selectedMonth)}月${int.parse(_selectedDay)}日';
    } else if (_selectedYear.isNotEmpty && _selectedMonth.isNotEmpty) {
      _selectedBirthDate = '${_selectedYear}年${int.parse(_selectedMonth)}月';
    } else if (_selectedYear.isNotEmpty) {
      _selectedBirthDate = '${_selectedYear}年';
    }
  }

  /// 获取API格式的出生日期 (yyyy-MM-dd)
  String _getApiBirthDate() {
    if (_selectedYear.isNotEmpty &&
        _selectedMonth.isNotEmpty &&
        _selectedDay.isNotEmpty) {
      return '$_selectedYear-$_selectedMonth-$_selectedDay';
    }
    return '';
  }

  Widget _buildScrollableDatePicker(String type, Function(String) onSelected) {
    List<String> items;
    String? initialValue;
    Function(String) actualOnSelected = onSelected;

    switch (type) {
      case '年':
        final currentYear = DateTime.now().year;
        items = List.generate(100, (index) => '${currentYear - 80 + index}');
        initialValue =
            _selectedYear.isNotEmpty ? _selectedYear : '${currentYear - 30}';
        break;
      case '月':
        items = List.generate(12, (index) => '${index + 1}');
        initialValue =
            _selectedMonth.isNotEmpty ? '${int.parse(_selectedMonth)}' : '1';
        actualOnSelected = (value) {
          onSelected(value.padLeft(2, '0'));
        };
        break;
      case '日':
        items = List.generate(31, (index) => '${index + 1}');
        initialValue =
            _selectedDay.isNotEmpty ? '${int.parse(_selectedDay)}' : '1';
        actualOnSelected = (value) {
          onSelected(value.padLeft(2, '0'));
        };
        break;
      default:
        items = [];
        initialValue = null;
    }

    return Container(
      height: 200.h,
      child: Stack(
        children: [
          // 选择指示器背景
          Positioned(
            top: 75.h,
            left: 0,
            right: 0,
            child: Container(
              height: 50.h,
              decoration: BoxDecoration(
                color: const Color(0xffF46425).withOpacity(0.1),
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
          ),
          // 滚动选择器
          _buildWheelPicker(
            items: items,
            onSelected: actualOnSelected,
            initialValue: initialValue,
          ),
        ],
      ),
    );
  }

  Widget _buildScrollablePicker({
    required List<String> items,
    required Function(String) onSelected,
    String? initialValue,
  }) {
    return Container(
      height: 200.h,
      child: Stack(
        children: [
          // 选择指示器背景
          Positioned(
            top: 75.h,
            left: 0,
            right: 0,
            child: Container(
              height: 50.h,
              decoration: BoxDecoration(
                color: const Color(0xffF46425).withOpacity(0.1),
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
          ),
          // 滚动选择器
          _buildWheelPicker(
            items: items,
            onSelected: onSelected,
            initialValue: initialValue,
          ),
        ],
      ),
    );
  }

  Widget _buildWheelPicker({
    required List<String> items,
    required Function(String) onSelected,
    String? initialValue,
  }) {
    // 计算初始索引
    int initialIndex = 0;
    if (initialValue != null && items.contains(initialValue)) {
      initialIndex = items.indexOf(initialValue);
    }

    final itemHeight = 50.h;
    final scrollController = ScrollController(
      initialScrollOffset: initialIndex * itemHeight,
    );

    // 初始化时调用一次选择回调
    WidgetsBinding.instance.addPostFrameCallback((_) {
      onSelected(items[initialIndex]);
    });

    return NotificationListener<ScrollNotification>(
      onNotification: (ScrollNotification notification) {
        if (notification is ScrollUpdateNotification ||
            notification is ScrollEndNotification) {
          // 滚动时实时计算中间位置并选中
          final centerOffset = notification.metrics.pixels + (200.h / 2) - 75.h;
          final index = (centerOffset / itemHeight).round();
          final clampedIndex = index.clamp(0, items.length - 1);
          onSelected(items[clampedIndex]);
        }
        return false;
      },
      child: ListView.builder(
        controller: scrollController,
        padding: EdgeInsets.symmetric(vertical: 75.h),
        itemCount: items.length,
        itemBuilder: (context, index) {
          return Container(
            height: 50.h,
            alignment: Alignment.center,
            child: Text(
              items[index],
              style: TextStyle(
                color: Colors.white,
                fontSize: 18.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildQuestionStep(String title, List<String> questions,
      List<List<String>> options, int startIndex) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          for (int i = 0; i < questions.length; i++) ...[
            _buildQuestionCard(questions[i], options[i], startIndex + i),
            if (i < questions.length - 1) SizedBox(height: 19.h),
          ],
        ],
      ),
    );
  }

  Widget _buildQuestionCard(
      String question, List<String> options, int questionIndex) {
    bool isMultipleChoice = question.contains('可多选');

    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: const Color(0xFF282528),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            question,
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
              color: Colors.white,
            ),
          ),
          SizedBox(height: 15.h),
          ...options
              .map((option) =>
                  _buildOption(option, questionIndex, isMultipleChoice))
              .toList(),
        ],
      ),
    );
  }

  Widget _buildOption(String option, int questionIndex, bool isMultipleChoice) {
    bool isSelected = _isOptionSelected(option, questionIndex);

    return Padding(
      padding: EdgeInsets.only(bottom: 10.h),
      child: GestureDetector(
        onTap: () => _onOptionTap(option, questionIndex, isMultipleChoice),
        child: Row(
          children: [
            Container(
              width: 20.w,
              height: 20.h,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(
                    color: isSelected ? const Color(0xffF46425) : Colors.white,
                    width: 1),
                color:
                    isSelected ? const Color(0xffF46425) : Colors.transparent,
              ),
              child: isSelected
                  ? const Icon(
                      Icons.check,
                      color: Colors.white,
                      size: 12,
                    )
                  : null,
            ),
            SizedBox(width: 12.w),
            Expanded(
              child: Text(
                option,
                style: TextStyle(
                  fontSize: 16.sp,
                  color: isSelected ? Colors.white : Color(0xffdedede),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  bool _isOptionSelected(String option, int questionIndex) {
    if (!_selectedOptions.containsKey(questionIndex)) {
      return false;
    }
    return _selectedOptions[questionIndex]!.contains(option);
  }

  void _onOptionTap(String option, int questionIndex, bool isMultipleChoice) {
    setState(() {
      if (!_selectedOptions.containsKey(questionIndex)) {
        _selectedOptions[questionIndex] = [];
      }

      if (isMultipleChoice) {
        // 多选逻辑
        if (_selectedOptions[questionIndex]!.contains(option)) {
          _selectedOptions[questionIndex]!.remove(option);
        } else {
          _selectedOptions[questionIndex]!.add(option);
        }
      } else {
        // 单选逻辑
        _selectedOptions[questionIndex] = [option];
      }
    });
  }

  /// 提交问卷数据
  Future<void> _submitQuestionnaire() async {
    try {
      // 验证必填信息
      if (!_validateRequiredFields()) {
        Toast.show('请完善个人信息');
        return;
      }

      // 显示加载页面
      _showCreatingPlanDialog();

      // 获取设备序列号
      final ringService = Get.find<RingService>();
      final deviceSn = ringService.getCurrentDeviceSn();

      // 构建问卷答案数据
      final exerciseAnswers = _buildAnswerList(0, 2); // 运动目标：问题0-1
      final sleepAnswers = _buildAnswerList(2, 5); // 睡眠目标：问题2-4
      final dietAnswers = _buildAnswerList(5, 8); // 饮食目标：问题5-7
      final emotionAnswers = _buildAnswerList(8, 10); // 情绪管理：问题8-9
      final periodAnswers = _buildAnswerList(10, 12); // 周期规划：问题10-11

      // 调用API提交问卷
      final response =
          await DefaultApi().addHealthQuestionPost<Map<String, dynamic>>(
        // deviceSn: deviceSn,
        sex: _selectedGender ?? '',
        height: _parseHeight(_selectedHeight ?? ''),
        weight: _parseWeight(_selectedWeight ?? ''),
        birthday: _getApiBirthDate(), // 使用API格式的日期
        career: _professionLogic.text,
        exerciseList: exerciseAnswers,
        sleepList: sleepAnswers,
        dietList: dietAnswers,
        emotionList: emotionAnswers,
        periodList: periodAnswers,
      );

      // 关闭加载对话框
      Get.back();

      if (response != null && response['data'] != null) {
        // 获取计划ID
        final planId = response['data']?.toString() ?? '';
        // 显示成功页面
        _showPlanCompleteDialog(planId);
      } else {
        Toast.show('问卷提交失败，请重试');
      }
    } catch (e) {
      // 关闭加载对话框
      if (Get.isDialogOpen ?? false) {
        Get.back();
      }
      print('提交问卷失败: $e');
      Toast.show('问卷提交失败，请重试');
    }
  }

  /// 显示计划生成中的对话框
  void _showCreatingPlanDialog() {
    print('显示加载对话框');
    Get.dialog(
      PopScope(
        canPop: false, // 禁止返回
        child: Scaffold(
          backgroundColor: Colors.black54,
          body: Center(
            child: Container(
              width: 353.w,
              height: 255.h,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(Assets.plan.isCreatingBg.path),
                  fit: BoxFit.fill,
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(height: 70.h),
                  const CircularProgressIndicator(
                    color: Color(0xffF46425),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }

  /// 显示计划生成完成的对话框
  void _showPlanCompleteDialog(String planId) {
    print('显示完成对话框，planId: $planId');
    Get.dialog(
      PopScope(
        canPop: true, // 禁止返回
        child: Scaffold(
          backgroundColor: Colors.black54,
          body: Center(
            child: Container(
              width: 353.w,
              height: 497.h,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage(Assets.plan.planComplectBcg.path),
                  fit: BoxFit.fill,
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SizedBox(height: 230.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // 返回首页按钮
                      GestureDetector(
                        onTap: () {
                          final statusLogic = Get.find<StatusLogic>();
                          statusLogic.changeTabIndex(0);
                          // 然后跳转到状态页
                          Get.offAllNamed(StatusRoutes.status);
                        },
                        child: Container(
                          width: 136.w,
                          height: 48.h,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(24.r),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            '返回首页',
                            style: TextStyle(
                              color: Colors.black,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(width: 20.w),
                      // 查看计划按钮
                      GestureDetector(
                        onTap: () {
                          print('点击查看计划');
                          Get.back(); // 关闭对话框
                          // 跳转到计划详情页
                          Get.toNamed(
                            ActionRoutes.questionnairePlan,
                            arguments: {'planId': planId},
                          );
                        },
                        child: Container(
                          width: 136.w,
                          height: 48.h,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(24.r),
                              border: Border.all(
                                  width: 1.w, color: Color(0xffD8D8D8))),
                          alignment: Alignment.center,
                          child: Text(
                            '查看计划',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
      barrierDismissible: false,
    );
  }

  /// 验证必填字段
  bool _validateRequiredFields() {
    return _selectedGender != null &&
        _selectedHeight != null &&
        _selectedWeight != null &&
        _selectedBirthDate != null &&
        _professionLogic.text.isNotEmpty;
  }

  /// 构建答案列表
  List<HealthQuestionAnswer> _buildAnswerList(int startIndex, int endIndex) {
    List<HealthQuestionAnswer> answers = [];

    for (int i = startIndex; i < endIndex; i++) {
      if (_selectedOptions.containsKey(i) && _selectedOptions[i]!.isNotEmpty) {
        // 将多个选项用逗号连接
        final answerText = _selectedOptions[i]!.join(', ');
        answers.add(HealthQuestionAnswer(
          questionId: i + 1, // 问题ID从1开始
          questionAnswer: answerText,
        ));
      }
    }

    return answers;
  }

  /// 解析身高数值
  int _parseHeight(String heightStr) {
    if (heightStr.isEmpty) return 0;
    final match = RegExp(r'(\d+)').firstMatch(heightStr);
    return match != null ? int.parse(match.group(1)!) : 0;
  }

  /// 解析体重数值
  int _parseWeight(String weightStr) {
    if (weightStr.isEmpty) return 0;
    final match = RegExp(r'(\d+)').firstMatch(weightStr);
    return match != null ? int.parse(match.group(1)!) : 0;
  }

  /// 提交基础信息（仅个人信息）
  Future<void> _submitBasicInfo() async {
    try {
      // 显示加载提示
      Toast.show('正在提交基础信息...');

      // 验证必填信息
      if (!_validateRequiredFields()) {
        Toast.show('请完善个人信息');
        return;
      }

      // 只提交基础信息，问卷部分为空
      final response =
          await DefaultApi().addHealthQuestionPost<Map<String, dynamic>>(
        // deviceSn: deviceSn,
        sex: _selectedGender ?? '',
        height: _parseHeight(_selectedHeight ?? ''),
        weight: _parseWeight(_selectedWeight ?? ''),
        birthday: _getApiBirthDate(), // 使用API格式的日期
        career: _professionLogic.text,
        exerciseList: [], // 空列表
        sleepList: [], // 空列表
        dietList: [], // 空列表
        emotionList: [], // 空列表
        periodList: [], // 空列表
      );

      if (response != null) {
        Toast.show('基础信息提交成功！');
        final statusLogic = Get.find<StatusLogic>();
        statusLogic.changeTabIndex(0);
        // 然后跳转到状态页
        Get.offAllNamed(StatusRoutes.status);
      } else {
        Toast.show('基础信息提交失败，请重试');
      }
    } catch (e) {
      print('提交基础信息失败: $e');
      Toast.show('基础信息提交失败，请重试');
    }
  }
}
